package Client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;

public class PerfectPointToPointLink {

	int port;
	private Socket connection;
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private ServerSocket server;
	private LinkedList<Message> delivery;
	boolean isServer;
	
	//Constructor
	public PerfectPointToPointLink(String mode,int port,String ipToConect) throws IOException, ClassNotFoundException{
	
		this.delivery = new LinkedList<Message>();
		//Server
		if( mode.equals("Server") ){
			
			isServer = true;
			server = new ServerSocket(this.port=port);

			
			while(true){
				System.out.println("Waiting For Connection....");
				connection = server.accept();
				System.out.println("Connection received from " + connection.getInetAddress().getHostName());
				
				//Data out
				out = new ObjectOutputStream(connection.getOutputStream());
				out.flush();
				
				//Data in
				in = new ObjectInputStream(connection.getInputStream());
				
				System.out.println(deliver());
				send(new  Message(new String("S:testeHeader"),new String("S:testMessage")));
				send(new  Message(new String("S:testeHeader"),new String("S:testMessage")));
				
				closeClientConnection();
			}
		}
		//Client
		else{

			isServer = false;	
			String IP = ipToConect == null? InetAddress.getLocalHost().getHostAddress() : ipToConect;
			
			System.out.println("Connect:"+IP);
			
			connection =  	new Socket(IP,this.port=port);
			
			in = 			new ObjectInputStream(connection.getInputStream());
			
			out = 			new ObjectOutputStream(connection.getOutputStream());
			out.flush();

		}
	}
	
	//Send Value
	public void send(Message value) throws IOException{
		out.writeObject(value);
		out.flush();
	}
	
	public Message deliver() throws IOException, ClassNotFoundException{
		Message m = (Message)in.readObject();
		
		if(!delivery.contains(m)){
			delivery.add(m);
			return m;
		}
		
		return null;
		
	}
	
	//Close Client Connection
	public void closeClientConnection() throws IOException{
		in.close();
		out.close();
		connection.close();
	}
	
	//Close all connections
	public void closeConection() throws IOException{
		in.close();
		out.close();
		connection.close();
		
		if (isServer)
			connection.close();
	}
	
	
}
